package com.whalefin.service;


import com.baidu.yun.channel.auth.ChannelKeyPair;
import com.baidu.yun.channel.client.BaiduChannelClient;
import com.baidu.yun.channel.exception.ChannelClientException;
import com.baidu.yun.channel.exception.ChannelServerException;
import com.baidu.yun.channel.model.PushUnicastMessageRequest;
import com.baidu.yun.channel.model.PushUnicastMessageResponse;
import com.baidu.yun.core.log.YunLogEvent;
import com.baidu.yun.core.log.YunLogHandler;
import com.whalefin.domain.BaiDuPush;
import com.whalefin.persistence.BaiDuPushMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * Created by cwj on 12/5/14.
 */
@Controller
public class iOSPushNotificationService {
//    private final static String API_KEY = "Ej3nm7WNhcdm4Ytb2NWq4YPI";
//    private final static String SECRIT_KEY = "cu5tG7GqX2PxrCjP3Mj67YWE7lr5Rxcb";
    private final static String API_KEY = "sdr1awqBnqh6ULitx0671fwH";
    private final static String SECRIT_KEY = "N5C73wNhcH1uBONMrOl1BQ2npsmKpabG";
    @Autowired
    private BaiDuPushMapper baiDuPushMapper;


    /**
     *
     * @param userID
     * @param msg
     * @param code
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/personalPush")
    public
    @ResponseBody
    Map<String , Objects> personalPush(Integer userID, String msg, String code) {
        Map result = new HashMap<String, Objects>();


        BaiDuPush push = baiDuPushMapper.queryPushUser(userID);
        if(push != null){
            String baiduId = push.getBaiduId();


            ChannelKeyPair pair = new ChannelKeyPair(API_KEY, SECRIT_KEY);
            // 2. 创建BaiduChannelClient对象实例



            //推送消息
            if (StringUtils.isNotBlank(baiduId)) {
                // 2. 创建BaiduChannelClient对象实例
                BaiduChannelClient channelClient = new BaiduChannelClient(pair);
                // 3. 若要了解交互细节，请注册YunLogHandler类
                channelClient.setChannelLogHandler(new YunLogHandler() {
                    @Override
                    public void onHandle(YunLogEvent event) {
                        // TODO Auto-generated method stub
                        System.out.println(event.getMessage());
                    }
                });
                try {
                    // 4. 创建请求类对象
                    PushUnicastMessageRequest request = new PushUnicastMessageRequest();

                    if (push.getDeviceType() == 3){
                        //android
                        request.setDeviceType(push.getDeviceType()); // device_type => 1: web 2: pc 3:android
                        request.setUserId(push.getBaiduId());
                        request.setMessage("{\"title\":\"黑板报\",\"description\":\"" + msg + "\",\"pushCode\":\"" + code + "\"}");
                        request.setMessageType(0);
                    }else if (push.getDeviceType() == 4){
                        //iOS
                        request.setDeviceType(push.getDeviceType()); // device_type => 1: web 2: pc 3:android
                        request.setUserId(push.getBaiduId());
                        request.setMessageType(1);
                        request.setMessage("{\"aps\":{\"alert\":\"" + msg + "\"},\"pushCode\":\"" + code + "\"}");
                        request.setDeployStatus(2);
                    }

                    System.out.print("message content:" + request.getMessage());
                    PushUnicastMessageResponse response = channelClient.pushUnicastMessage(request);
                    System.out.println("push amount : " + response.getSuccessAmount());
                } catch (ChannelClientException e) {
                    e.printStackTrace();
                } catch (ChannelServerException e) {
                    // 处理服务端错误异常
                    System.out.println(String.format(
                            "request_id: %d, error_code: %d, error_message: %s",
                            e.getRequestId(), e.getErrorCode(), e.getErrorMsg()));
                }
            }
        }
        result.put("push","success");
        return  result;
    }


}
